import ErrorBoundary from '@/components/ErrorBoundary';
import IconFont from '@/components/IconFont';
import BasicLayout from '@/layouts/BasicLayout';
import Login from '@/pages/Login';
import { Spin } from 'antd';
import { isEmpty } from 'lodash';
import React, { lazy, Suspense } from 'react';
import type { NonIndexRouteObject } from 'react-router-dom';
import { Outlet } from 'react-router-dom';

function lazyLoadFn(LazyComponent: ReturnType<typeof lazy>) {
  return (
    <Suspense
      fallback={
        <div>
          <Spin spinning={true}>组件加载中...</Spin>
        </div>
      }
    >
      <LazyComponent />
    </Suspense>
  );
}

export interface IRouteItem extends Omit<NonIndexRouteObject, 'children' | 'element'> {
  key: string;
  label?: string;
  icon?: React.ReactNode;
  children?: IRouteItem[];
  element: React.ReactNode; //React.LazyExoticComponent<any> |
  hidden?: boolean;
  menuActiveKey?: string; //hidden:true 的路由，匹配选中的菜单项
}

const rootChildren: IRouteItem[] = [
  {
    path: 'plannedManage',
    key: 'plannedManage',
    label: '计划管理',
    icon: <IconFont type="icon-jihuaguanli"></IconFont>,
    errorElement: <ErrorBoundary />,
    element: <Outlet />,
    children: [
      {
        path: 'studyPlanNew',
        key: 'studyPlanNew',
        label: '学习计划(新)',
        element: lazyLoadFn(
          lazy(() => import(/* webpackChunkName: "PlanManage-StudyPlanNew" */ '@/pages/PlanManage/StudyPlanNew')),
        ),
      },
      {
        path: 'addStudyPlanNew',
        key: 'addStudyPlanNew',
        label: '添加学习计划(新)',
        hidden: true,
        menuActiveKey: 'studyPlanNew',
        element: lazyLoadFn(
          lazy(() => import(/* webpackChunkName: "PlanManage-AddStudyPlanNew" */ '@/pages/PlanManage/AddStudyPlanNew')),
        ),
      },
      {
        path: 'examPlanNew',
        key: 'examPlanNew',
        label: '考试计划(新)',
        element: lazyLoadFn(
          lazy(() => import(/* webpackChunkName: "PlanManage-ExamPlanNew" */ '@/pages/PlanManage/ExamPlanNew')),
        ),
      },
      {
        path: 'addExamPlanNew',
        key: 'addExamPlanNew',
        label: '添加考试计划(新)',
        hidden: true,
        menuActiveKey: 'examPlanNew',
        element: lazyLoadFn(
          lazy(() => import(/* webpackChunkName: "PlanManage-AddExamPlanNew" */ '@/pages/PlanManage/AddExamPlanNew')),
        ),
      },
      {
        path: 'studyPlan',
        key: 'studyPlan',
        label: '学习计划(旧)',
        element: lazyLoadFn(
          lazy(() => import(/* webpackChunkName: "PlanManage-StudyPlan" */ '@/pages/PlanManage/StudyPlan')),
        ),
      },
      {
        path: 'addStudyPlan',
        key: 'addStudyPlan',
        label: '添加学习计划(旧)',
        hidden: true,
        menuActiveKey: 'studyPlan',
        element: lazyLoadFn(
          lazy(() => import(/* webpackChunkName: "PlanManage-AddStudyPlan" */ '@/pages/PlanManage/AddStudyPlan')),
        ),
      },
      {
        path: 'examPlan',
        key: 'examPlan',
        label: '考试计划(旧)',
        element: lazyLoadFn(
          lazy(() => import(/* webpackChunkName: "PlanManage-ExamPlan" */ '@/pages/PlanManage/ExamPlan')),
        ),
      },
      {
        path: 'addExamPlan',
        key: 'addExamPlan',
        label: '添加考试计划(旧)',
        hidden: true,
        menuActiveKey: 'examPlan',
        element: lazyLoadFn(
          lazy(() => import(/* webpackChunkName: "PlanManage-AddExamPlan" */ '@/pages/PlanManage/AddExamPlan')),
        ),
      },
    ],
  },
  {
    path: 'plaResLib',
    key: 'plaResLib',
    label: '平台资源库',
    icon: <IconFont type="icon-pingtaiziyuanku"></IconFont>,
    errorElement: <ErrorBoundary />,
    element: <Outlet />,
    children: [
      {
        path: 'plaCoursewarePack',
        key: 'plaCoursewarePack',
        label: '课件包',
        element: lazyLoadFn(
          lazy(
            () =>
              import(
                /* webpackChunkName: "PlatformResourceLibrary-CoursewarePackageLibrary" */ '@/pages/PlatformResourceLibrary/CoursewarePackageLibrary'
              ),
          ),
        ),
      },
      {
        path: 'plaTestPaper',
        key: 'plaTestPaper',
        label: '试卷',
        element: lazyLoadFn(
          lazy(
            () =>
              import(
                /* webpackChunkName: "PlatformResourceLibrary-ExamLibrary" */ '@/pages/PlatformResourceLibrary/ExamLibrary'
              ),
          ),
        ),
      },
    ],
  },
  {
    path: 'cusResLib',
    key: 'cusResLib',
    label: '自建资源库',
    icon: <IconFont type="icon-zijianziyuanku"></IconFont>,
    errorElement: <ErrorBoundary />,
    element: <Outlet />,
    children: [
      {
        path: 'courseWare',
        key: 'courseWare',
        label: '课件',
        element: lazyLoadFn(
          lazy(() => import(/* webpackChunkName: "resourceLibrary-courseware" */ '@/pages/CusResLib/CourseWare')),
        ),
      },
      {
        path: 'addVideoCourseWare',
        key: 'addVideoCourseWare',
        label: '添加视频课件',
        hidden: true,
        menuActiveKey: 'courseWare',
        element: lazyLoadFn(
          lazy(
            () =>
              import(
                /* webpackChunkName: "resourceLibrary-addVideoCourseWare" */ '@/pages/CusResLib/AddVideoCourseWare'
              ),
          ),
        ),
      },
      {
        path: 'addGraphicCourseWare',
        key: 'addGraphicCourseWare',
        label: '添加图文课件',
        hidden: true,
        menuActiveKey: 'courseWare',
        element: lazyLoadFn(
          lazy(
            () =>
              import(
                /* webpackChunkName: "resourceLibrary-addGraphicCourseWare" */ '@/pages/CusResLib/AddGraphicCourseWare'
              ),
          ),
        ),
      },
      {
        path: 'addPdfCourseWare',
        key: 'addPdfCourseWare',
        label: '添加pdf课件',
        hidden: true,
        menuActiveKey: 'courseWare',
        element: lazyLoadFn(
          lazy(
            () =>
              import(/* webpackChunkName: "resourceLibrary-addPdfCourseWare" */ '@/pages/CusResLib/AddPdfCourseWare'),
          ),
        ),
      },
      {
        path: 'examination',
        key: 'examination',
        label: '考题',
        element: lazyLoadFn(
          lazy(() => import(/* webpackChunkName: "resourceLibrary-examination" */ '@/pages/CusResLib/Examination')),
        ),
      },
      {
        path: 'addMChoiceQue',
        key: 'addMChoiceQue',
        label: '添加多选题',
        hidden: true,
        menuActiveKey: 'examination',
        element: lazyLoadFn(
          lazy(() => import(/* webpackChunkName: "resourceLibrary-addMChoiceQue" */ '@/pages/CusResLib/AddMChoiceQue')),
        ),
      },
      {
        path: 'addSChoiceQue',
        key: 'addSChoiceQue',
        label: '添加单选题',
        hidden: true,
        menuActiveKey: 'examination',
        element: lazyLoadFn(
          lazy(() => import(/* webpackChunkName: "resourceLibrary-addSChoiceQue" */ '@/pages/CusResLib/AddSChoiceQue')),
        ),
      },
      {
        path: 'addJudgeQue',
        key: 'addJudgeQue',
        label: '添加判断题',
        hidden: true,
        menuActiveKey: 'examination',
        element: lazyLoadFn(
          lazy(() => import(/* webpackChunkName: "resourceLibrary-addJudgeQue" */ '@/pages/CusResLib/AddJudgeQue')),
        ),
      },
      {
        path: 'testPaper',
        key: 'testPaper',
        label: '试卷',
        element: lazyLoadFn(
          lazy(() => import(/* webpackChunkName: "resourceLibrary-testPaper" */ '@/pages/CusResLib/TestPaper')),
        ),
      },
      {
        path: 'addTestPaper',
        key: 'addTestPaper',
        label: '添加试卷',
        hidden: true,
        menuActiveKey: 'testPaper',
        element: lazyLoadFn(
          lazy(() => import(/* webpackChunkName: "resourceLibrary-addTestPaper" */ '@/pages/CusResLib/AddTestPaper')),
        ),
      },
      {
        path: 'package',
        key: 'package',
        label: '课件包',
        element: lazyLoadFn(
          lazy(() => import(/* webpackChunkName: "resourceLibrary-Package" */ '@/pages/CusResLib/Package')),
        ),
      },
    ],
  },
  {
    path: 'statistics',
    key: 'statistics',
    label: '统计',
    icon: <IconFont type="icon-tongji"></IconFont>,
    errorElement: <ErrorBoundary />,
    element: <Outlet />,
    children: [
      {
        path: 'learningStatistics',
        key: 'learningStatistics',
        label: '学习统计',
        element: lazyLoadFn(
          lazy(
            () =>
              import(/* webpackChunkName: "cusResLib-LearningStatistics" */ '@/pages/Statistics/LearningStatistics'),
          ),
        ),
      },
      {
        path: 'driverCardList',
        key: 'driverCardList',
        label: '司机学习卡',
        menuActiveKey: 'cardList',
        element: lazyLoadFn(
          lazy(() => import(/* webpackChunkName: "OfflineStudy-DriverCardList" */ '@/pages/PlanManage/DriverCardList')),
        ),
      },
      {
        path: 'entPersonNoStudy',
        key: 'entPersonNoStudy',
        label: '计划未学习情况',
        hidden: true,
        menuActiveKey: 'learningStatistics',
        element: lazyLoadFn(
          lazy(
            () =>
              import(
                /* webpackChunkName: "cusResLib-EntPersonStudyTable" */ '@/pages/Statistics/LearningStatistics/EntPersonNoStudyTable'
              ),
          ),
        ),
      },
      {
        path: 'entPersonStudy',
        key: 'entPersonStudy',
        label: '计划学习详情',
        hidden: true,
        menuActiveKey: 'learningStatistics',
        element: lazyLoadFn(
          lazy(
            () =>
              import(
                /* webpackChunkName: "cusResLib-EntPersonStudyTable" */ '@/pages/Statistics/LearningStatistics/EntPersonStudyTable'
              ),
          ),
        ),
      },
      {
        path: 'history',
        key: 'history',
        label: '历史学习情况',
        hidden: true,
        menuActiveKey: 'learningStatistics',
        element: lazyLoadFn(
          lazy(
            () =>
              import(
                /* webpackChunkName: "cusResLib-HistoryStudy" */ '@/pages/Statistics/LearningStatistics/HistoryStudy'
              ),
          ),
        ),
      },
    ],
  },
  {
    path: 'safeService',
    key: 'safeService',
    label: '安学行服务',
    icon: <IconFont type="icon-anxuehangfuwu"></IconFont>,
    errorElement: <ErrorBoundary />,
    element: <Outlet />,
    children: [
      {
        path: 'buyService',
        key: 'buyService',
        label: '购买服务',
        element: lazyLoadFn(
          lazy(() => import(/* webpackChunkName: "safeService-buyService" */ '@/pages/SafeService/BuyService')),
        ),
      },
      {
        path: 'bitAllocation',
        key: 'bitAllocation',
        label: '选择学员',
        element: lazyLoadFn(
          lazy(() => import(/* webpackChunkName: "safeService-bitAllocation" */ '@/pages/SafeService/BitAllocation')),
        ),
      },
      {
        path: 'billManage',
        key: 'billManage',
        label: '发票管理',
        element: lazyLoadFn(
          lazy(() => import(/* webpackChunkName: "safeService-billManage" */ '@/pages/SafeService/BillManage')),
        ),
      },
    ],
  },
  {
    path: 'ServiceAccountManage',
    key: 'ServiceAccountManage',
    label: '服务号管理',
    icon: <IconFont type="icon-anxuehangfuwu"></IconFont>,
    errorElement: <ErrorBoundary />,
    element: <Outlet />,
    children: [
      {
        path: 'Fans',
        key: 'Fans',
        label: '粉丝信息',
        element: lazyLoadFn(
          lazy(() => import(/* webpackChunkName: "ServiceAccountManage-fans" */ '@/pages/ServiceAccountManage/Fans')),
        ),
      },
      {
        path: 'PostResource',
        key: 'PostResource',
        label: '发布动态',
        element: lazyLoadFn(
          lazy(
            () =>
              import(
                /* webpackChunkName: "ServiceAccountManage-PostResource" */ '@/pages/ServiceAccountManage/PostResource'
              ),
          ),
        ),
      },
    ],
  },
  {
    path: 'oHai',
    key: 'oHai',
    label: '给瓯海嵌入的页面',
    icon: <IconFont type="icon-anxuehangfuwu"></IconFont>,
    errorElement: <ErrorBoundary />,
    element: <Outlet />,
    hidden: true,
    children: [
      {
        path: 'Learn',
        key: 'Learn',
        label: '学习统计',
        element: lazyLoadFn(lazy(() => import(/* webpackChunkName: "OHai-Learn" */ '@/pages/OHai/Learn'))),
      },
      {
        path: 'Ins',
        key: 'Ins',
        label: '保险统计',
        element: lazyLoadFn(lazy(() => import(/* webpackChunkName: "OHai-Ins" */ '@/pages/OHai/Ins'))),
      },
    ],
  },
  {
    path: 'SafeStudySet',
    key: 'SafeStudySet',
    label: '设置',
    icon: <IconFont type="icon-anxuehangfuwu"></IconFont>,
    errorElement: <ErrorBoundary />,
    element: <Outlet />,
    children: [
      {
        path: 'studyCardRules',
        key: 'studyCardRules',
        label: '学习卡规则',
        menuActiveKey: 'cardRules',
        element: lazyLoadFn(
          lazy(() => import(/* webpackChunkName: "OfflineStudy-StudyCardRules" */ '@/pages/PlanManage/StudyCardRules')),
        ),
      },
    ],
  },
];

const appRouter: IRouteItem[] = [
  {
    path: '/', // element: <Navigate to='/home' />
    key: '/',
    element: <BasicLayout />,
    errorElement: <ErrorBoundary />,
    children: rootChildren,
  },
  {
    path: '/login',
    key: 'login',
    element: <Login />,
    errorElement: <ErrorBoundary />,
  },
];

// 微应用引入整个应用
function geMicroAppRouter(nestType: number): IRouteItem[] {
  console.log('----geMicroAppRouter---nestType---:', nestType);
  return [
    {
      path: '/',
      key: '/',
      element: <BasicLayout nestType={nestType} />,
      errorElement: <ErrorBoundary />,
      children: rootChildren,
    },
  ];
}

// 树结构 递归查找
function getCurRouteItem(keyParam: string, rootChildrenParam: IRouteItem[]): IRouteItem | undefined {
  for (let i = 0; i < rootChildrenParam.length; i++) {
    const { key, children } = rootChildrenParam[i];
    if (key === keyParam) return rootChildrenParam[i];
    if (children && children.length > 0) {
      const tempRootCurrItem: IRouteItem | undefined = getCurRouteItem(keyParam, children);
      if (!isEmpty(tempRootCurrItem)) return tempRootCurrItem;
    }
  }
}

/**
 * 嵌入模块页面的router
 * @param nestType  1:应用， 2：模块， 3： 页面 4: iframe嵌套页面
 * @param nestPath '/cusResLib' || ["/cusResLib", "/plaResLib"]
 * @returns
 */
const getModuleORouter: (nestType: number, nestPath: string | string[]) => IRouteItem[] = (nestType, nestPath) => {
  const nestPathArrays = typeof nestPath === 'string' ? [nestPath] : nestPath.filter((pathName: string) => pathName);
  const rootCurrItems: IRouteItem[] = [];
  nestPathArrays.forEach((pathName: string) => {
    const pathArray = pathName.split('/').filter((name: string) => !isEmpty(name));
    const lastKey = pathArray.pop();
    if (lastKey) {
      const rootCurrItem = getCurRouteItem(lastKey, rootChildren);
      if (rootCurrItem) {
        rootCurrItems.push(rootCurrItem);
      }
    }
  });
  const initialPagePath =
    rootCurrItems[0] && rootCurrItems[0].children && rootCurrItems[0].children[0].path
      ? rootCurrItems[0].path + '/' + rootCurrItems[0].children[0].path
      : '';

  if (rootCurrItems.length <= 0 || !initialPagePath) {
    return [
      {
        path: '/',
        key: '/',
        element: <ErrorBoundary />,
        errorElement: <ErrorBoundary />,
      },
    ];
  }

  return [
    {
      path: '/',
      key: '/',
      element: <BasicLayout nestType={nestType} nestPath={initialPagePath} routes={rootCurrItems} />,
      errorElement: <ErrorBoundary />,
      children: rootCurrItems,
    },
  ];
};

export { appRouter, geMicroAppRouter, getModuleORouter, rootChildren };
